package com.chao.wind3j.base.config.commonConfig.requestLogConfig.requestInterceptor;

import com.alibaba.fastjson.JSON;
import com.chao.wind3j.base.config.commonConfig.CommonProperties;
import com.chao.wind3j.base.config.commonConfig.requestLogConfig.requestWrapper.CustomRequestWrapper;
import com.chao.wind3j.base.config.commonConfig.requestLogConfig.requestWrapper.CustomResponseWrapper;
import com.chao.wind3j.model.dataBaseModel.Wind3Request;
import com.chao.wind3j.model.dataBaseModel.Wind3User;
import com.chao.wind3j.service.Wind3RequestService;
import com.chao.wind3j.util.DateFormat;
import com.chao.wind3j.util.DateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class LogInterceptor implements HandlerInterceptor {

  private final CommonProperties commonProperties;

  private final Wind3RequestService wind3RequestService;

  public LogInterceptor(CommonProperties commonProperties, Wind3RequestService wind3RequestService) {
    this.commonProperties = commonProperties;
    this.wind3RequestService = wind3RequestService;
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    var wrapperRequest = new CustomRequestWrapper(request, this.commonProperties);
    var wind3Request = new Wind3Request();
    this.handleRequestInfo(wrapperRequest, wind3Request, handler);
    return true;
  }
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
  }

  private void handleRequestInfo(CustomRequestWrapper requestWrapper, Wind3Request wind3Request, Object handler) {
    var requestInfo = requestWrapper.getRequestInfo();
    wind3Request.setRequestContent(JSON.toJSONString(requestInfo));
    wind3Request.setRequestDateTime(DateUtil.getDateFromFormat(requestInfo.getRequestTime(), DateFormat.format_yyyy_MM_dd_HH_mm_ss));
    wind3Request.setRequestMethodName(handler.toString());
//    this.wind3RequestService.insertWind3Request(wind3Request);
    this.printRequestInfo(requestWrapper);
  }

  private void printRequestInfo(CustomRequestWrapper requestWrapper) {
    System.out.println(requestWrapper.getRequestInfo());
  }
}
